package com.atguigu.flink.chapter11.function;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/21 9:59
 */
public class Flink01_Scalar {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        DataStreamSource<String> stream = env.fromElements("hello", "atguigu", "Hello");
        env.setParallelism(2);
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        Table table = tenv.fromDataStream(stream, $("word"));
        
        // 可以把字母从小写变成大写的函数// 1. 注册函数
        
        // 2. 使用
        // 2.1 在tableapi中使用
        // 2.1.1 内联方式使用
        /*table
            .select($("word"), call(MyUpper.class, $("word")))
            .execute()
            .print();
        */
        // 2.1.2 注册后使用
        /*tenv.createTemporaryFunction("my_upper", MyUpper.class);
        table
            .select($("word"), call("my_upper", $("word")))
            .execute()
            .print();*/
        
        // 2.2 在sql中使用  必须先注册
        tenv.createTemporaryFunction("my_upper", MyUpper.class);
    
        tenv.sqlQuery("select word, my_upper(word) from " + table).execute().print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static class MyUpper extends ScalarFunction {
        public String eval(String s) {
            if (s != null) {
                return s.toUpperCase();
            }
            return null;
        }
    }
}
